#include "../logs/log.hpp"
#include <thread>
#include <vector>
void bench(const std::string& name, size_t thread_count, size_t msg_count, size_t msg_len)
{
    //1.根据日志器名称获取日志器
    mylog::Logger::ptr logger = mylog::getLogger(name);
    if(logger.get() == nullptr)  return;
    //2.创建线程
    std::vector<std::thread> threads;
    std::vector<double> cost_array(thread_count);
    std::string msg(msg_len, 'F');
    int count = msg_count / thread_count;
    for(int i = 0; i < thread_count; i++)
    {
        threads.emplace_back([&, i](){
            auto start=std::chrono::high_resolution_clock::now();
            for(int j = 0; j < count; j++)
            {
                logger->fatal("%s",msg.c_str());
            }
            auto end=std::chrono::high_resolution_clock::now();

            //4.统计时间
            std::chrono::duration<double> cost=end-start;
            cost_array[i] = cost.count();
            std::cout<<"\t线程"<<i<<": "<<"\t输出日志数量:"<<msg_count<<", 耗时:"<<cost.count()<<"s"<<std::endl;
        });
    }
    for(int i = 0; i < thread_count; i++)
    {
        threads[i].join();
    }
    //5.输出结果
    double cost_max = cost_array[0];
    for(int i = 1; i < thread_count; i++)
    {
        cost_max = cost_max > cost_array[i] ? cost_max : cost_max; 
    }

    size_t msg_per_sec = msg_count / cost_max;
    size_t size_per_sec = (msg_count * msg_len) / (cost_max * 1024) ;
    std::cout<<"\t总耗时"<< cost_max << "s\n";
    std::cout<<"每秒输出日志数量: "<<msg_per_sec<<"条\n";
    std::cout<<"每秒输出日志大小: "<<size_per_sec<<"kb\n";
}

void syncbench()
{
    std::unique_ptr<mylog::LoggerBuilder> loggerbuild(new mylog::GlobalLoggerBuilder());
    loggerbuild->buildLoggerName("sync_logger");
    loggerbuild->buildLimitLevel(mylog::LogLevel::value::WARN);
    loggerbuild->buildLoggerType(mylog::LoggerType::LOGGER_SYNC);
    loggerbuild->buildformater("%m%n");
    loggerbuild->buildSinks<mylog::FileSink>("./logfile/sync.log");
    loggerbuild->build();
    bench("sync_logger", 3, 5000000, 100);
}

void asyncbench()
{
    std::unique_ptr<mylog::LoggerBuilder> loggerbuild(new mylog::GlobalLoggerBuilder());
    loggerbuild->buildLoggerName("async_logger");
    loggerbuild->buildLimitLevel(mylog::LogLevel::value::WARN);
    loggerbuild->buildLoggerType(mylog::LoggerType::LOGGER_ASYNC);
    loggerbuild->buildformater("%m%n");
    loggerbuild->buildSinks<mylog::FileSink>("./logfile/async.log");
    loggerbuild->buildEnableUnSafeAsync();
    loggerbuild->build();
    bench("async_logger", 3, 5000000, 100);
}
int main()
{
    //syncbench();
    asyncbench();
    return 0;
}